package com.cpf.controller;

import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author cpf email: cpfprogrammer@163.com
 * @date 2022/5/30 下午1:42
 */
@RestController
@RequestMapping("/cs")
public class CookieSessionController {

    @PostMapping("/cookie")
    public Object cookie(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + "=" + cookie.getValue());
                response.addCookie(cookie);
            }
        }
        return response.getHeaderNames();
    }

    @PostMapping("/session")
    public Object session(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession(true);
        session.setMaxInactiveInterval(10);
        session.setAttribute("username", "cpf");
        session.setAttribute("password", "123456");
        return response.getHeaderNames();
    }

    @GetMapping("/session")
    public Object info(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        Map<String, Object> map = new HashMap<>();
        Iterator<String> iterator = session.getAttributeNames().asIterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            map.put(next, session.getAttribute(next));
        }
        return map;
    }
}
